package com.dms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.dms.bean.Fix;
import com.dms.util.DBUtil;

public class FixDao {
	private static DBUtil	db	= new DBUtil();
	public static boolean add(Fix fix) {
		boolean val = false;
		if (fix!=null) {
			String sql = "insert into fix (content,name,stuID,dormID) values(?,?,?,?)";
			try {
				db.update(sql,fix.getContent(),fix.getName(),fix.getStuID(),fix.getDormID());
				val=true;
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			try {
				db.close();
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return val;
	}
	
	public static ArrayList<Fix> list(String stuID) {
		ArrayList<Fix> fixs = new ArrayList<Fix>();
		String sql;
		if(stuID.equals("admin")){
			sql = "select * from fix order by date desc";
		}
		else{
			sql = "select * from fix where stuID =? order by date desc";
		}
		try {
			ResultSet rs;
			if(stuID.equals("admin")){
				rs = db.query(sql);
			}
			else{
				rs = db.query(sql, stuID);
			}
			while (rs.next()) {
				fixs.add(new Fix(rs.getInt("fixID"),rs.getString("stuID"),rs.getString("name"),rs.getString("content"),rs.getInt("state"), rs.getTimestamp("date")));
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		try {
			db.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return fixs;
	}
	
	public static Fix find(int fixID) {
		boolean val = false;
		Fix fix = new Fix();
		if (fixID >=0) {
			String sql = "select name,content,state,date from fix where fixID=?";
			ResultSet rs = null;
			try {
				rs = db.query(sql, fixID);
				val = (rs != null && rs.next()) ? true : false;
				if (val) {
					fix.setFixID(fixID);
					fix.setName(rs.getString("name"));
					fix.setContent(rs.getString("content"));
					fix.setState(rs.getInt("state"));
					fix.setDate(rs.getTimestamp("date"));
				}
			}
			catch (Exception e) {
				val = false;
				e.printStackTrace();
			}
			try {
				db.close();
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return fix;
	}
	
		public static boolean save(Fix fix) throws Exception {
			boolean var = false;
			try {
				if (fix != null) {
					String sql = "update fix set content =?,state=? where fixID =?";
					db.update(sql, fix.getContent(), fix.getState(), fix.getFixID());
					var = true;
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			try {
				db.close();
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
			return var;
		}
		public static boolean delete(int fixID) {
			boolean var = false;
			try {
					String sql = "delete from fix where fixID =?";
					db.update(sql, fixID);
					var = true;
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			try {
				db.close();
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
			return var;
		}
}
